package com.hxzy.shop.marketing.config;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.hxzy.shop.constant.AuthConstant;
import com.hxzy.shop.entity.Merchant;
import com.hxzy.shop.marketing.utils.MerchantThreadLocalUtils;
import com.hxzy.shop.utils.WebUtil;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName MybatisPlusConfig
 * @Author wengjt
 * @Date 2021/7/31 16:49
 * @Description
 **/
@Configuration
@MapperScan("com.hxzy.shop.marketing.mapper")
public class MybatisPlusConfig {
    private static String MERCHANT_ID="merchantId";
    @Value("${ignore.table}")
    private List<String> ignoreTables;
    /**
     * 新多租户插件配置,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存万一出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new TenantLineHandler() {


            @Override
            public Expression getTenantId() {
                String merchantId = null;
                HttpServletRequest request = WebUtil.getRequest();
                if (ObjectUtil.isNotEmpty(request)) {
                    merchantId = request.getHeader(AuthConstant.MERCHANT_ID);
                    if (ObjectUtil.isEmpty(merchantId)) {
                        Merchant merchant = MerchantThreadLocalUtils.getMerchant();
                        merchantId = merchant.getId().toString();
                    }
                }else {
                    Merchant merchant = MerchantThreadLocalUtils.getMerchant();
                    merchantId = merchant.getId().toString();
                }
                return new LongValue(merchantId);
            }

            @Override
            public String getTenantIdColumn() {
                return "merchant_id";
            }

            // 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
            @Override
            public boolean ignoreTable(String tableName) {
                boolean flag=false;
                for (String name:
                        ignoreTables) {
                    if (name.equals(tableName)){
                        flag=true;
                    }
                }
                return flag;
            }
        }));

        return interceptor;
    }
}
